package me.shurufa.fragments;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import de.greenrobot.event.EventBus;
import me.shurufa.R;
import me.shurufa.model.LoginResponse;
import me.shurufa.net.API;
import me.shurufa.net.BaseResponse;
import me.shurufa.net.RequestServerTask;
import me.shurufa.utils.Constants;
import me.shurufa.utils.HttpUtil;
import me.shurufa.utils.Utils;

/**
 * 在此写用途
 *
 * @FileName: me.shurufa.fragments.RegisterFragment.java
 * @author: kHRYSTAL
 * @email: 723526676@qq.com
 * @date: 2016-01-15 10:03
 */
public class RegisterFragment extends BaseFragment implements View.OnClickListener {

    @Bind(R.id.mobile_edit)
    EditText mobileEdit;
    @Bind(R.id.verify_code_edit)
    EditText verifyCodeEdit;
    @Bind(R.id.verify_code_button)
    TextView verifyCodeButton;
    @Bind(R.id.password_edit)
    EditText passwordEdit;
    @Bind(R.id.register_button)
    Button registerButton;
    @Bind(R.id.go_login)
    TextView goLogin;
    @Bind(R.id.notice_layout)
    LinearLayout noticeLayout;
    @Bind(R.id.notice_text)
    TextView noticeText;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_register, container, false);
        return view;
    }

    @Override
    protected void initUI(View view) {
        super.initUI(view);
        registerButton.setOnClickListener(this);
        noticeText.setOnClickListener(this);
        goLogin.setOnClickListener(this);
        verifyCodeButton.setOnClickListener(this);

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.register_button:
                if (isInputValid()) {
                    doRegister();
                }
                break;
            case R.id.verify_code_button:
                getVerifyCode();
                break;
            case R.id.notice_text:
            case R.id.go_login:
                EventBus.getDefault().post(new Intent(Constants.ACTION_LOGIN_SWITCH));
                break;
        }
    }

    private boolean isInputValid() {
        String mobile = mobileEdit.getText().toString();
        if (mobile.length() != getResources().getInteger(R.integer.mobile_length)) {
            Utils.showToast(R.string.please_input_mobile_number);
            return false;
        }
        String verifyCode = verifyCodeEdit.getText().toString();
        if (verifyCode.length() != getResources().getInteger(R.integer.verify_code_length)) {
            Utils.showToast(R.string.invalid_verify_code);
            return false;
        }
        String password = passwordEdit.getText().toString();
        if (password.length() < getResources().getInteger(R.integer.min_password_length)) {
            Utils.showToast(R.string.password_too_short);
            return false;
        }
//        wtf? 设计稿注册不设置昵称
//        String nick = nickEdit.getText().toString().trim();
//        if (nick.length() < getResources().getInteger(R.integer.min_nick_length)) {
//            Utils.showToast(R.string.nick_too_short);
//            return false;
//        }
//        if (nick.length()>getResources().getInteger(R.integer.max_nick_length)){
//            Utils.showToast(R.string.nick_too_long);
//            return false;
//        }
        return true;
    }

    private void doRegister() {
        final Map<String, Object> params = new HashMap<>();
        params.put("mobile", mobileEdit.getText().toString());
        params.put("password", passwordEdit.getText().toString());
        params.put("code", verifyCodeEdit.getText().toString());
        new RequestServerTask<LoginResponse>(LoginResponse.class, this, getString(R.string
                .registering)) {
            @Override
            protected String requestServer() {
                return HttpUtil.post(API.USER_REGISTER, params);
            }

            @Override
            protected void onSuccess(LoginResponse result) {
                Utils.showToast(R.string.register_success);
//                保留方法 返回的User不全 只有Uid有用
//                Settings.setCurrentUid(result.data.uid);
//TODO                跳转至登录 该fragment内容是否清空？
                EventBus.getDefault().post(new Intent(Constants.ACTION_LOGIN_SWITCH));
            }

        }.start();
    }

    private void getVerifyCode() {
        final Map<String, Object> params = new HashMap<>();

        params.put("mobile", mobileEdit.getText().toString());
        params.put("type","register");
        new RequestServerTask<BaseResponse>(BaseResponse.class, this, getString(R.string
                .getting_registration_sms)) {
            @Override
            protected String requestServer() {
                return HttpUtil.post(API.SEND_CAPTCHA, params);
            }

            @Override
            protected void onSuccess(BaseResponse result) {
                Utils.showToast(R.string.get_registration_sms_success);
                mHandler.sendEmptyMessage(MSG_COUNT_DOWN_BEGIN);
            }

        }.setDefaultErrMsg(R.string.get_registration_sms_failed).start();
    }

//    倒计时 start
    private static final int MSG_COUNT_DOWN = 30;

    private static final int MSG_COUNT_DOWN_BEGIN = 31;

    private static final int MSG_COUNT_DOWN_FINISHED = 32;

    private int countDown = Constants.SMS_COUNT_DOWN_TIME;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_COUNT_DOWN_BEGIN:
                    verifyCodeButton.setEnabled(false);
                    sendEmptyMessage(MSG_COUNT_DOWN);
                    break;
                case MSG_COUNT_DOWN:
                    countDown--;
                    verifyCodeButton.setText(
                            String.format(getString(R.string.count_down_time_left), countDown));
                    if (countDown > 0) {
                        sendEmptyMessageDelayed(MSG_COUNT_DOWN, 1000);
                    } else {
                        verifyCodeButton.setText(getString(R.string.get_verify_code));
                        verifyCodeButton.setEnabled(true);
                        countDown = Constants.SMS_COUNT_DOWN_TIME;
                    }
                    break;
                case MSG_COUNT_DOWN_FINISHED:
                    break;

            }

        }
    };

    private void finishCountdown() {
        countDown = 0;
        mHandler.removeMessages(MSG_COUNT_DOWN);
    }
//    倒计时 end

    @Override
    public void onDestroy() {
        finishCountdown();
        super.onDestroy();
    }
}
